// 打包方式：串行(series)  并行(parallel)
import path from "path";
import { copyFile, mkdir } from "fs/promises";
import { copy } from "fs-extra";
import { parallel, series } from "gulp";
import fs from "fs-extra";
import { buildOutput, mainOutput, mainPackage } from "./utils/paths";
import type { TaskFunction } from "gulp";
import { run, withTaskName } from "./utils";
import { buildConfig } from "./utils/config";
// 任务执行器 gulp 任务名 就会执行对应的任务
export * from "./tasks";
// gulp 不叫打包，做代码转化 vite

//复制package
export const copyFiles = () =>
  Promise.all([copyFile(mainPackage, path.join(mainOutput, "package.json"))]);

//复制声明文件
export const copyTypesDefinitions: TaskFunction = (done) => {
  const src = path.resolve(buildOutput, "types", "packages");
  const copyTypes = (module) =>
    withTaskName(`copyTypes:${module}`, () =>
      copy(src, `${buildConfig[module].output.path}`, {
        recursive: true,
      })
    );

  return parallel(copyTypes("esm"), copyTypes("cjs"))(done);
};

//复制样式
// export const copyFullStyle = async () => {
//   await mkdir(path.resolve(mainOutput, "dist"), { recursive: true });
//   await copyFile(
//     path.resolve(mainOutput, "theme-chalk/index.css"),
//     path.resolve(mainOutput, "dist/index.css")
//   );
// };

const rmDist = () => async () => {
  await fs.removeSync(`${buildOutput}`);
};

/**
 * 1. 打包样式
 * 2. 打包工具方法
 * 3. 打包所有组件
 * 4. 打包每个组件
 * 5. 生成一个组件库
 * 6. 发布组件
 */
export default series(
  rmDist(),
  withTaskName("createOutput", () => mkdir(mainOutput, { recursive: true })),
  parallel(
    withTaskName("buildModules", () => run("pnpm run build buildModules")), //构建 Bundless包
    // withTaskName("buildFullModules", () =>
    //   run("pnpm run build buildFullModules")
    // ) // 执行build命令时会调用rollup，给rollup传参数buildFullComponent，那么就会执行导出任务叫buildFullComponent
    withTaskName("generateTypesDefinitions", () =>
      run("pnpm run build generateTypesDefinitions")
    ), //生成声明文件
    series(
      withTaskName("buildThemeChalk", () =>
        run("pnpm run -C packages/theme-chalk build")
      )
      //copyFullStyle
    )
  ),
  parallel(copyTypesDefinitions, copyFiles)
);
